/**
 * Created by LeungZ on 2016/10/17.
 */
class Ctrl {
    constructor(imageSrv, $scope, ctgNotification) {
        "ngInject";
        this._imgSrv = imageSrv;
        this._notification = ctgNotification;
        this.volumes = [];
        this.logVolumes = [];

        if ($scope.service) {
            if ($scope.service.baseCtrl) {
                this.podAppName = $scope.service.baseCtrl.podAppName;
                this.appImg = $scope.service.baseCtrl.appImg;
                this.podNum = $scope.service.baseCtrl.podNum;
                this.podCpu = $scope.service.baseCtrl.podCpu;
                this.podMem = $scope.service.baseCtrl.podMem;
                this.groups = $scope.service.baseCtrl.groups;
                this.volumes = $scope.service.baseCtrl.volumes || [];
                this.logVolumes = $scope.service.baseCtrl.logVolumes || [];
                if (this.appImg && this.appImg.ver && this.appImg.id) this.getImgVerList();
            }
            $scope.service.baseCtrl = this;
        }
    }

    getImgVerList() {
        this.verLoading = true;
        this._imgSrv.getImageVers({id: this.appImg.id, currentPage: 1, page: 99}).then(data=> {
            this.appImgVerList = data.list;
            if (this.appImg.ver) this.appImg.ver = _.findWhere(this.appImgVerList, {id: this.appImg.ver.id});
        }).catch(data=> {
            this._notification.error("获取版本数据有误, 请重新选择应用镜像");
        }).finally(()=> {
            this.verLoading = false;
        })
    }

    getAppImgVer(id) {
        this.appImgVerList = null;
        this.appImg.id = id;
        this.appImg.ver = null;

        this.getImgVerList();
    }

    volAdd() {
        this.volumes.push({
            name: '',
            hostPath: '',
            mountPath: ''
        });
    }

    volRemove(index) {
        this.volumes.splice(index, 1);
    }

    checkVolName(index) {
        if (this.volumes[index].name) {
            for (var i in this.volumes) {
                if (this.volumes[i].name == this.volumes[index].name && i != index) {
                    return this.baseForm['volName' + index].$setValidity('duplicate', false);
                }
            }
            this.baseForm['volName' + index].$setValidity('duplicate', true);
        }
    }

    logVolAdd() {
        this.logVolumes.push({
            name: '',
            path: ''
        })
    }

    logVolRemove(index) {
        this.logVolumes.splice(index, 1);
    }

    checkLogVolName(index) {
        if (this.logVolumes[index].name) {
            for (var i in this.logVolumes) {
                if (this.logVolumes[i].name == this.logVolumes[index].name && i != index) {
                    return this.baseForm['logVolName' + index].$setValidity('duplicate', false);
                }
            }
            this.baseForm['logVolName' + index].$setValidity('duplicate', true);
        }
    }
}
export default Ctrl